//
//  ZMShadowView.swift
//  TravelForUser
//
//  Created by Rowling on 2020/8/26.
//  Copyright © 2020 智蚂优服. All rights reserved.
//

import UIKit


class ZMShadowView : UIView {
    @IBInspectable var shadowColor : UIColor = .black
    @IBInspectable var shadowOpacity : CGFloat = 0.1
    @IBInspectable var shadowRadius : CGFloat = 4
    @IBInspectable var shadowOffset : CGSize = CGSize(width: 3, height: 3)
    @IBInspectable var shadowSetOpen : Bool = true
    let disposeBag = DisposeBag()
    var shadowLayer : ZMShadowLayer?
    
    override var isHidden: Bool {
        set {
            super.isHidden = newValue
            shadowLayer?.isHidden = newValue
        }
        get {
            super.isHidden
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        addShadowLayer()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addShadowLayer()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    
    
    func addShadowLayer() {
        if shadowSetOpen {
            shadowLayer = ZMShadowLayer()
            shadowLayer!.isHidden = isHidden
            if let shadowLayer = shadowLayer {
                rx.observe(Bool.self, "isHidden").subscribe { (e) in
                    guard let temp = e.element, let hide = temp else {return}
                    shadowLayer.isHidden = hide
                }.disposed(by: disposeBag)
            }
            layerSizeToFit()
        }
    }
    
    func layerSizeToFit() {
        if shadowSetOpen, let shadowLayer = shadowLayer {
            let fixFream = frame
            shadowLayer.frame = fixFream
            shadowLayer.cornerRadius = shadowRadius
//            if shadowColor != UIColor.black {
//                shadowLayer.backgroundColor = shadowColor.cgColor
//            } else {
                shadowLayer.backgroundColor = backgroundColor?.cgColor
//            }
            shadowLayer.masksToBounds = false
            shadowLayer.shadowColor = shadowColor.cgColor
            shadowLayer.shadowOffset = shadowOffset
            shadowLayer.shadowOpacity = Float(shadowOpacity)
            shadowLayer.shadowRadius = shadowRadius
            superview?.layer.insertSublayer(shadowLayer, below: layer)
        }
    }
    
    override func layoutSubviews() {
        superview?.layoutSubviews()
        layerSizeToFit()
    }
}

class ZMShadowLayer : CALayer {
    
}
